
package com.kerrykidz.workflow.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.bpmn.behavior.UserTaskActivityBehavior;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.pvm.PvmActivity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.pvm.process.ProcessDefinitionImpl;
import org.activiti.engine.impl.pvm.process.TransitionImpl;
import org.activiti.engine.impl.task.TaskDefinition;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kerrykidz.system.util.ConstantUtil;
import com.kerrykidz.system.util.DataSourceUtil;
import com.kerrykidz.system.util.UserUtil;
import com.kerrykidz.system.vo.FormSyncVo;
import com.kerrykidz.system.vo.UserInfo;
import com.kerrykidz.workflow.dao.mapper.ActivitiEntityMapper;
import com.kerrykidz.workflow.dao.model.ActivitiEntity;
import com.kerrykidz.workflow.service.IWorkflowService;
import com.kerrykidz.workflow.util.FormSQLUtil;
import com.kerrykidz.workflow.vo.OptHisVo;
import com.kerrykidz.workflow.vo.TypeVo;
import com.kerrykidz.workflow.vo.WorkflowParamVo;
import com.kerrykidz.workflow.vo.WorkflowVo;
import com.rdp.framework.exception.RDPException;

/**
 * 工作流Service层
 * @author zhuss
 *
 */
@Service
public class WorkflowServiceimpl implements IWorkflowService{

	private static Logger logger = LoggerFactory.getLogger(WorkflowServiceimpl.class);
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    protected TaskService taskService;
    @Autowired
    protected HistoryService historyService;
    @Autowired
    protected RepositoryService repositoryService;
    @Autowired
    private IdentityService identityService;
    
    @Autowired
    private ActivitiEntityMapper activitiEntityMapper;
    
    @Autowired
    DataSourceUtil ds;
	
    /**
     * 加载流程文件
     * @throws RDPException
     */
    public void deploy(String key) throws RDPException{
    	String path = "disagrams/"+key+".bpmn";
    	logger.debug("reqeust : path = "+ path);
    	repositoryService.createDeployment().addClasspathResource(path).deploy();
    } 
    
    /**
     * 
     * 启动流程
     * @param: @param key 比如请假是leave,价格是price,库存调整是stock,限时打折discount,采购订单order,付款pay
     * @param: @param businessKey 业务ID
     * @param: @param user 登录用户
     * @param: @return
     * @param: @throws RDPException
     * @return: WorkflowServiceimpl
     * @throws
     */
	@Override
	public String startWorkflow(String key ,String businessKey,UserInfo user) throws RDPException{
		ProcessDefinition pd = getProcessDefinitionByKey(key);
		if(null == pd)
			deploy(key);
		// 用来设置启动流程的人员ID
        identityService.setAuthenticatedUserId(user.getUserId());
        Map<String, Object> variables = new HashMap<String, Object>();
		variables.put("applyUserId", user.getUserId());
		variables.put("handleAdvice", ConstantUtil.WORKFLOW_STATUS_CREATE);
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(key, businessKey, variables);
        if(null == processInstance)
        	throw new RDPException("网络异常,请稍后再试");
        //睡眠1秒,为了解决默认起始节点和实际起始节点相同开始时间的问题
        try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
        Map<String,Object> map = getNextActivity(processInstance.getId(), user);
        if(null != map.get("startActivityId"))
        	variables.put("startActivityId", map.get("startActivityId"));
        if(null != map.get("nextTaskDefinition")){
        	TaskDefinition t = (TaskDefinition) map.get("nextTaskDefinition");
        	freeTransfer(processInstance.getId(), t.getKey(), user.getUserId(), variables);
        }	 
        return processInstance.getId();
	}
	
	/**
	 * 递交和重新申请
	 * @param WorkflowParamVo 工作流参数类
	 * @throws RDPException
	 * @date: 2014年9月5日
	 */
	public ProcessInstance complete(WorkflowParamVo workflowparam) throws RDPException {
		Map<String, Object> variables = new HashMap<String, Object>();
		List<Task> taskList  = taskService.createTaskQuery().processInstanceId(workflowparam.getProcessInstanceId()).list();
		if(taskList.size() != 0){
			for(Task t : taskList){
				if(StringUtils.isNotBlank(workflowparam.getHandleParam()) && null != workflowparam.getHandleParamValue())
					variables.put(workflowparam.getHandleParam(), workflowparam.getHandleParamValue());
				variables.put(t.getId()+"handleReason",workflowparam.getHandleReason());
				if(StringUtils.isNotBlank(workflowparam.getUserInfo().getUserId())){
					// 由于流程用户上下文对象是线程独立的，所以要在需要的位置设置，要保证设置和获取操作在同一个线程中
			        Authentication.setAuthenticatedUserId(workflowparam.getUserInfo().getUserId());//批注人的名称  一定要写，不然查看的时候不知道人物信息
			        taskService.addComment(t.getId(), t.getProcessInstanceId(), workflowparam.getHandleAdviceDes());
				}
				taskService.complete(t.getId(), variables);
			}
		}
		ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(workflowparam.getProcessInstanceId()).singleResult();
		return pi;
	}
	
	/**
	 * 签收任务，分配任务
	 * @param WorkflowParamVo 
	 * @throws RDPException
	 */
	public void claimTask(WorkflowParamVo workflowparam)throws RDPException {
		List<Task> taskList  = taskService.createTaskQuery().processInstanceId(workflowparam.getProcessInstanceId()).list();
		for(Task task:taskList){
			taskService.claim(task.getId(), workflowparam.getClaimUserId());
		}
	}
	
	/**
	 * 根据用户查询待办任务
	 * @param userId
	 * @return
	 */
	public List<Task> findTodoTasks(String userId) throws RDPException{
		logger.debug("request key = {} , userId ={}",userId);
		List<Task> tasks = new ArrayList<Task>();
		// 根据当前人的ID查询
		TaskQuery todoQuery = taskService.createTaskQuery().taskAssignee(userId).active()
				.orderByTaskId().desc().orderByTaskCreateTime().desc();
		// List<Task> todoList = todoQuery.listPage(pageParams[0],
		// pageParams[1]);
		List<Task> todoList = todoQuery.list();
		// 根据当前人未签收的任务
		TaskQuery claimQuery = taskService.createTaskQuery().taskCandidateUser(userId)
				.active().orderByTaskId().desc().orderByTaskCreateTime().desc();
		List<Task> unsignedTasks = claimQuery.list();
		// 合并
		tasks.addAll(todoList);
		tasks.addAll(unsignedTasks);
		return tasks;
	}
	
	/**
	 * 查询用户的已结束的任务
	 * @param userId
	 * @return
	 */
	public List<HistoricProcessInstance> findfinishedTasks(String key,String userId) throws RDPException{
		logger.debug("request key = {} , userId ={}",key,userId);
		List<HistoricProcessInstance> list = historyService.createHistoricProcessInstanceQuery().processDefinitionKey(key).startedBy(userId).finished().orderByProcessInstanceEndTime().desc().list();
		return list;
	}
	
	/**
	 * 获取指定流程的处理意见历史列表
	 * @param processInstanceId
	 * @return
	 * @throws Exception
	 */
	public List<OptHisVo> findOpinions(String processInstanceId,UserInfo user) throws RDPException{
		logger.debug("request processInstanceId = {} ",processInstanceId);
		List<OptHisVo> volist = new ArrayList<OptHisVo>();
		List<ActivitiEntity> list = ds.queryHisOptByProcId(processInstanceId,user);
		if(null == list)
			list = activitiEntityMapper.queryHisOptByProcId(processInstanceId);
		for(ActivitiEntity a : list){
			OptHisVo ovo = a.changeOptHisVo();
			volist.add(ovo);
		}
		return volist;
	}
	
	/**
	 * 删除(关闭)流程保留历史
	 * @param WorkflowParamVo 工作流参数类
	 * @throws RDPException
	 * @date: 2014年9月5日
	 */
	@Override
	public void deleteProcessInstance(WorkflowParamVo workflowparam) throws RDPException{
		List<Task> taskList  = taskService.createTaskQuery().processInstanceId(workflowparam.getProcessInstanceId()).list();
		if(taskList.size() != 0){
			for(Task t : taskList){
				if(StringUtils.isNotBlank(workflowparam.getUserInfo().getUserId())){
					// 由于流程用户上下文对象是线程独立的，所以要在需要的位置设置，要保证设置和获取操作在同一个线程中
			        Authentication.setAuthenticatedUserId(workflowparam.getUserInfo().getUserId());//批注人的名称  一定要写，不然查看的时候不知道人物信息
			        taskService.addComment(t.getId(), workflowparam.getProcessInstanceId(),ConstantUtil.WORKFLOW_STATUS_CLOSE);
				}
			}
		}
		runtimeService.deleteProcessInstance(workflowparam.getProcessInstanceId(), ConstantUtil.WORKFLOW_STATUS_CLOSE);
	}

	/**
	 * 根据ID获取流程定义
	 */
	public ProcessDefinition getProcessDefinition(String processDefinitionId)
			throws RDPException {
		ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult();
        return processDefinition;
	}

	/**
	 * 根据业务类Id查找对应的Task
	 */
	public List<Task> getTaskByBusinessKey(String key) throws RDPException {
		List<Task> t  = taskService.createTaskQuery().processInstanceBusinessKey(key).list();
		return t;
	}

	/**
	 * 根据业务ID获取流程实例
	 */
	public ProcessInstance getProcessInstanceByBusinessKey(String businessKey)
			throws RDPException {
		return runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(businessKey).singleResult();
	}

	/**
	 * 根据ID获取Task（Task的ID是动态的，delete之前的insert新task）
	 */
	public Task getTaskById(String id) throws RDPException {
		return taskService.createTaskQuery().taskId(id).singleResult();
	}

	

	/**
	 * 根据流程ID获取历史流程实例
	 */
	public HistoricProcessInstance getHistoricProcessInstanceById(String id)
			throws RDPException {
		return historyService.createHistoricProcessInstanceQuery().processInstanceId(id).singleResult();
	}

	/**
	 * 根据Key查找最新的流程定义
	 */
	public ProcessDefinition getProcessDefinitionByKey(String key)
			throws RDPException {
		return repositoryService.createProcessDefinitionQuery().processDefinitionKey(key).latestVersion().singleResult();
	}

	/**
	 * 根据流程ID获取流程实例
	 */
	public ProcessInstance getProcessInstanceById(String id)
			throws RDPException {
		ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(id).singleResult();
		return pi;
	}
	

	/**
	 * 退回到起点
	 * @param WorkflowParamVo 工作流参数类
	 * @throws Exception
	 */
	public void backProcessToStart(WorkflowParamVo workflowparam)throws RDPException{
		Map<String,Object> variables = new HashMap<String,Object>();
		variables.put("isBack", true);
		variables.put("handleAdvice",  ConstantUtil.WORKFLOW_STATUS_BACK);
		/*if(StringUtils.isNotBlank(workflowparam.getHandleParam()) && null != workflowparam.getHandleParamValue())
			variables.put(workflowparam.getHandleParam(), workflowparam.getHandleParamValue());*/
		//获取起始节点
		//HistoricActivityInstanceEntity starthaie = (HistoricActivityInstanceEntity) historyService.createHistoricActivityInstanceQuery().activityType("userTask").processInstanceId(processInstanceId).finished().orderByHistoricActivityInstanceEndTime().asc().listPage(0, 1).get(0);
		//当前节点:可能是并行的节点所以是List
		//List<HistoricActivityInstance> currhaieList =  historyService.createHistoricActivityInstanceQuery().activityType("userTask").processInstanceId(processInstanceId).unfinished().list();
		//for(HistoricActivityInstance currhaie:currhaieList ){
		//}
		ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(workflowparam.getProcessInstanceId()).singleResult();
		if(null != instance){
			Task t = taskService.createTaskQuery().processInstanceId(instance.getId()).list().get(0);
			variables.put(t.getId()+"handleReason",workflowparam.getHandleReason());
			if(null != getHistoricVariableInstanceByPorcessId(instance.getId()).get("startActivityId"))
				freeTransfer(instance.getId(),(String)getHistoricVariableInstanceByPorcessId(instance.getId()).get("startActivityId"),workflowparam.getUserInfo().getUserId(),variables);
		}
	}

	/**
	 * 自由流转
	 */
	public void freeTransfer(String processInstanceId,String activityId,String userId,Map<String,Object> variables) throws RDPException {
		// 取得当前任务
        HistoricTaskInstance currTask = historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstanceId).unfinished().singleResult();
        // 取得流程实例
        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        // 取得流程定义
        //ProcessDefinitionEntity definition = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService).getDeployedProcessDefinition(currTask.getProcessDefinitionId());
    	// 当前节点    
        ActivityImpl currActivity = findActivitiImpl(currTask.getId(), null);    
        //获取上一步这个流程流向: userTask(上一步) -- >  flow --> userTask(当前) ，List表示可能是并发步骤
        //List<PvmTransition> upTransitionList = currActivity.getIncomingTransitions();
        // 清空当前流向 ，临时保存当前流向：userTask(当前) --> flow --> userTask(下一步)   
        List<PvmTransition> currPvmTransitionList = clearTransition(currActivity); 
        //创建出口，这里也可以创建多个出口针对于并发操作
        // 创建新流向    
        TransitionImpl newTransition = currActivity.createOutgoingTransition(); 
        // 目标节点    
        ActivityImpl pointActivity = findActivitiImpl(currTask.getId(), activityId);  
        if(null == pointActivity){ //如果目标节点不存在,回退到前一步
        	/*List<TransitionImpl> newTransitions = new ArrayList<TransitionImpl>();
            for (PvmTransition upTransition : upTransitionList) {
                PvmActivity upActivity = upTransition.getSource();
                pointActivity = findActivitiImpl(taskId,upActivity.getId());
                newTransition.setDestination(pointActivity);
                newTransitions.add(newTransition);
            }*/
        	throw new RDPException("起始节点不存在!");
        }else{
        	// 设置新流向的目标节点    
            newTransition.setDestination(pointActivity);  
        }
        // 执行转向任务  :getTaskDefinitionKey=managerAudit  
        List<Task> tasks = taskService.createTaskQuery().processInstanceId(instance.getId()).taskDefinitionKey(currTask.getTaskDefinitionKey()).list();
        for (Task task : tasks) {
        	Authentication.setAuthenticatedUserId(userId);//批注人的名称  一定要写，不然查看的时候不知道人物信息
		    taskService.addComment(task.getId(), task.getProcessInstanceId(), (String)variables.get("handleAdvice"));
            taskService.complete(task.getId(), variables);
            //historyService.deleteHistoricTaskInstance(task.getId());
        } 
        // 删除目标节点新流入    
        pointActivity.getIncomingTransitions().remove(newTransition);    
        // 还原以前流向    
        restoreTransition(currActivity, currPvmTransitionList); 
	}
	
	 /**  
     * 根据任务ID和节点ID获取活动节点 <br>  
     *   
     * @param taskId   任务ID  
     * @param activityId    活动节点ID <br>   如果为null或""，则默认查询当前活动节点 <br>    如果为"end"，则查询结束节点 <br>  
     * @return  
     * @throws Exception  
     */    
    public  ActivityImpl findActivitiImpl(String taskId, String activityId) throws RDPException {    
    	//根据任务ID获得任务实例
        TaskEntity task = (TaskEntity) taskService.createTaskQuery().taskId(taskId).singleResult();  
    	// 取得流程定义    
        ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService).getDeployedProcessDefinition(task.getProcessDefinitionId());   
    
        // 获取当前活动节点ID    
        if (StringUtils.isEmpty(activityId)) {    
            activityId = task.getTaskDefinitionKey();    
        }    
        // 根据流程定义，获取该流程实例的结束节点    
        if (activityId.toUpperCase().equals("END")) {    
            for (ActivityImpl activityImpl : processDefinition.getActivities()) {    
                List<PvmTransition> pvmTransitionList = activityImpl.getOutgoingTransitions();    
                if (pvmTransitionList.isEmpty()) {    
                    return activityImpl;    
                }    
            }    
        }    
        // 根据节点ID，获取对应的活动节点    
        ActivityImpl activityImpl = ((ProcessDefinitionImpl) processDefinition).findActivity(activityId);    
        return activityImpl;    
    }  
    
    /**  
     * 清空指定活动节点流向  
     *   
     * @param activityImpl  
     *            活动节点  
     * @return 节点流向集合  
     */    
    private  List<PvmTransition> clearTransition(ActivityImpl activityImpl) {    
        // 存储当前节点所有流向临时变量    
        List<PvmTransition> oriPvmTransitionList = new ArrayList<PvmTransition>();    
        // 获取当前节点所有流向，存储到临时变量，然后清空    
        List<PvmTransition> pvmTransitionList = activityImpl    
                .getOutgoingTransitions();    
        for (PvmTransition pvmTransition : pvmTransitionList) {    
            oriPvmTransitionList.add(pvmTransition);    
        }    
        pvmTransitionList.clear();    
        return oriPvmTransitionList;    
    }  
    
    /**  
     * 还原指定活动节点流向  
     *   
     * @param activityImpl   活动节点  
     * @param oriPvmTransitionList   原有节点流向集合  
     */    
    private  void restoreTransition(ActivityImpl activityImpl,    
            List<PvmTransition> oriPvmTransitionList) {    
        // 清空现有流向    
        List<PvmTransition> pvmTransitionList = activityImpl    
                .getOutgoingTransitions();    
        pvmTransitionList.clear();    
        // 还原以前流向    
        for (PvmTransition pvmTransition : oriPvmTransitionList) {    
            pvmTransitionList.add(pvmTransition);    
        }    
    }

   
	/**
	 * 获取流程实例的最新的历史节点
	 * @param id
	 * @return
	 * @throws RDPException
	 */
	public List<HistoricActivityInstance> getNewestHistoricActivityInstanceByPorcessId(
			String id) throws RDPException {
		List<HistoricActivityInstance> hailist = new ArrayList<HistoricActivityInstance>();
		if(StringUtils.isNotBlank(id)) {
			//未结束的节点
			hailist = historyService.createHistoricActivityInstanceQuery().activityType("userTask").processInstanceId(id).unfinished().list();
			if(hailist.size() == 0)
				hailist = historyService.createHistoricActivityInstanceQuery().processInstanceId(id).activityType("userTask").orderByHistoricActivityInstanceEndTime().desc().finished().listPage(0, 1);
		}else{
			List<HistoricProcessInstance> hpi = getHistoricProcessInstanceList();
			for(HistoricProcessInstance h :hpi){
				List<HistoricActivityInstance> hais = historyService.createHistoricActivityInstanceQuery().processInstanceId(h.getId()).activityType("userTask").unfinished().orderByHistoricActivityInstanceEndTime().desc().list();	
				if(hais.size() != 0)
					hais = historyService.createHistoricActivityInstanceQuery().processInstanceId(h.getId()).activityType("userTask").unfinished().orderByHistoricActivityInstanceEndTime().desc().listPage(0, 1);
				hailist.addAll(hais) ;
			}
		}
		return hailist;
	}
	
	public List<HistoricProcessInstance> getHistoricProcessInstanceList() throws RDPException{
		return historyService.createHistoricProcessInstanceQuery().list();
	}
	
	/**
	 * 获取流程实例的所有的历史任务的节点
	 */
	public List<HistoricActivityInstance> getAllHistoricActivityInstanceByPorcessId(
			String id) throws RDPException {
		if(StringUtils.isNotBlank(id)) {
			return historyService.createHistoricActivityInstanceQuery().processInstanceId(id).activityType("userTask").list();
		}else
			return historyService.createHistoricActivityInstanceQuery().activityType("userTask").list();
	}

	/**
	 * 得到流程相关属性
	 *
	 * @param: @param processInstanceId
	 * @param: @param status
	 * @param: @return
	 * @param: @throws RDPException
	 * @return: WorkflowStatusVo
	 * @throws
	 */
	@Override
	public WorkflowVo getWorkflowVo(String processInstanceId,
			String status,UserInfo user) throws RDPException {
		WorkflowVo vo = new WorkflowVo();
		if (status.equals("2")) {
			if (StringUtils.isNotBlank(processInstanceId)) {
				Map<String, Object> map = getHistoricVariableInstanceByPorcessId(processInstanceId);
				if (null != map.get("isBack"))
					vo.setIsBack(String.valueOf(map.get("isBack")));
				if (null == map.get("startActivityId"))
					vo.setStartActivityId("applyUser");
				else
					vo.setStartActivityId((String) map.get("startActivityId"));

				vo.setStatusDesc(ConstantUtil.WORKFLOW_STATUS_START3);
				ActivitiEntity t = ds.queryCurrtTaskByProcId(processInstanceId,
						user,0);
				if (null == t)
					t = ds.queryCurrtTaskByProcId(processInstanceId,
							user,1);
				if (null == t)
					t = activitiEntityMapper.queryCurrtTaskByProcId(
							processInstanceId, user.getUserId());
				if (null != t) {
					vo.setStatusDesc(t.getName());
					vo.setIsStartUser("0");
					if (StringUtils.isNotBlank(vo.getIsBack())
							&& t.getTaskDefKey()
									.equals(vo.getStartActivityId())) {
						vo.setIsStartUser("1");
						if (vo.getStartActivityId().equals("managerAudit"))
							vo.setStatusDesc(ConstantUtil.WORKFLOW_STATUS_START2
									+ "("
									+ ConstantUtil.WORKFLOW_STATUS_BACK
									+ ")");
						else
							vo.setStatusDesc(ConstantUtil.WORKFLOW_STATUS_START1
									+ "("
									+ ConstantUtil.WORKFLOW_STATUS_BACK
									+ ")");
					}
					vo.setCurrtOptUser(t.getUserName());
					//vo.setIsStartUser(t.getIsStartUser());
					vo.setIsCurrtOpt(t.getIsCurrtOpt());
				}
			}
		}
		if(status.equals("1")){
			vo.setStatusDesc(ConstantUtil.WORKFLOW_STATUS_CG);
		} else if (status.equals("3")) {
			vo.setStatusDesc(ConstantUtil.WORKFLOW_STATUS_COMPLETE);
			vo.setResult(ConstantUtil.WORKFLOW_STATUS_YES);
		}else if(status.equals("4")){
			vo.setStatusDesc(ConstantUtil.WORKFLOW_STATUS_COMPLETE);
			vo.setResult(ConstantUtil.WORKFLOW_STATUS_NO);
		}else if(status.equals("5"))
			vo.setStatusDesc(ConstantUtil.WORKFLOW_STATUS_CLOSE);
		return vo;
	}
	
	/**
	 * 根据当前登录用户获取下一步节点
	 * @param procInstId
	 * @param user
	 * @date: 2014年9月10日
	 */
	public Map<String,Object> getNextActivity(String procInstId,UserInfo user){
		Map<String,Object> map = new HashMap<String,Object>();
		String processDefinitionId = historyService.createHistoricProcessInstanceQuery().processInstanceId(procInstId).singleResult().getProcessDefinitionId(); 
		ProcessDefinitionEntity def = (ProcessDefinitionEntity) ((RepositoryServiceImpl)repositoryService).getDeployedProcessDefinition(processDefinitionId); 
		//执行实例  
        ExecutionEntity execution = (ExecutionEntity) runtimeService.createProcessInstanceQuery().processInstanceId(procInstId).singleResult(); 
        //当前实例的执行到哪个节点  
        String activitiId = execution.getActivityId();  
		//获得当前任务的所有节点  
        List<ActivityImpl> activitiList = def.getActivities();  
        for(ActivityImpl activityImpl:activitiList){  
        	if(activityImpl.getProperties().get("type").equals("userTask")){
        			TaskDefinition taskDefinition = ((UserTaskActivityBehavior) activityImpl
        					.getActivityBehavior()).getTaskDefinition();
        			if(taskDefinition.getCandidateGroupIdExpressions().size()!=0){
            			if(user.getRoleList().contains(taskDefinition.getCandidateGroupIdExpressions().toArray()[0].toString())){
            				map.put("startActivityId", taskDefinition.getKey());
            				taskDefinition = nextTaskDefinition(activityImpl, activityImpl.getId(),null);  
            				map.put("nextTaskDefinition", taskDefinition);
            				return map;
            			}
            		}else if(taskDefinition.getCandidateUserIdExpressions().size() !=0){
            			if(user.getUserId().equals(taskDefinition.getCandidateUserIdExpressions().toArray()[0])){
            				map.put("startActivityId", taskDefinition.getKey());
            				taskDefinition = nextTaskDefinition(activityImpl, activityImpl.getId(),null);  
            				map.put("nextTaskDefinition", taskDefinition);
            				return map;
            			}else{
            				if(activitiId.equals(activityImpl.getId())){
                				taskDefinition = nextTaskDefinition(activityImpl, activityImpl.getId(),null);  
                				map.put("nextTaskDefinition", taskDefinition);
                				map.put("startActivityId", activitiId);
                				return map;
                			}
            			}
            		}else{
        				if(activitiId.equals(activityImpl.getId())){
            				taskDefinition = nextTaskDefinition(activityImpl, activityImpl.getId(),null);  
            				map.put("nextTaskDefinition", taskDefinition);
            				map.put("startActivityId", activitiId);
            				return map;
            			}
        			}
        		}
        }  
    	return map;
	}
	
	/** 
     * 下一个任务节点 
     * @param activityImpl 
     * @param activityId 
     * @param elString 
     * @return 
     */  
	private TaskDefinition nextTaskDefinition(ActivityImpl activityImpl,
			String activityId, String elString) {
		if ("userTask".equals(activityImpl.getProperty("type"))
				&& !activityId.equals(activityImpl.getId())) {
			TaskDefinition taskDefinition = ((UserTaskActivityBehavior) activityImpl
					.getActivityBehavior()).getTaskDefinition();
			// taskDefinition.getCandidateGroupIdExpressions().toArray();
			return taskDefinition;
		} else {
			List<PvmTransition> outTransitions = activityImpl
					.getOutgoingTransitions();
			List<PvmTransition> outTransitionsTemp = null;
			for (PvmTransition tr : outTransitions) {
				PvmActivity ac = tr.getDestination(); // 获取线路的终点节点
				if ("exclusiveGateway".equals(ac.getProperty("type"))) {
					outTransitionsTemp = ac.getOutgoingTransitions();
					if (outTransitionsTemp.size() == 1) {
						return nextTaskDefinition(
								(ActivityImpl) outTransitionsTemp.get(0)
										.getDestination(), activityId, elString);
					} else if (outTransitionsTemp.size() > 1) {
						for (PvmTransition tr1 : outTransitionsTemp) {
							Object s = tr1.getProperty("conditionText");
							if (elString.equals(StringUtils.trim(s.toString()))) {
								return nextTaskDefinition(
										(ActivityImpl) tr1.getDestination(),
										activityId, elString);
							}
						}
					}
				} else if ("userTask".equals(ac.getProperty("type"))) {
					return ((UserTaskActivityBehavior) ((ActivityImpl) ac)
							.getActivityBehavior()).getTaskDefinition();
				}
			}
			return null;
		}
	}

	/**
	 * 
	 * 获取所有的流程定义
	 * @param: @return
	 * @param: @throws RDPException
	 * @return: WorkflowServiceimpl
	 * @throws
	 */
	@Override
	public List<TypeVo> queryProcDef() throws RDPException {
		UserInfo user = UserUtil.getUserFromSession();
		List<TypeVo> typeList =  new  ArrayList<TypeVo>();
		List<ActivitiEntity> list = ds.queryProcDef(user.getBranId());
		if(null == list)
			list = activitiEntityMapper.queryProcDef();
		for(ActivitiEntity ae : list){
			TypeVo vo = new TypeVo();
			vo.setValue(ae.getName());
			vo.setKey(ae.getKey());
			typeList.add(vo);
		}
		return typeList;
	}
	
	 /**
     * 获取流程实例的所有参数
     */
	public Map<String,Object> getHistoricVariableInstanceByPorcessId(
			String id) throws RDPException {
		Map<String,Object> map = new HashMap<String,Object>();
		List<HistoricVariableInstance> list = historyService.createHistoricVariableInstanceQuery().processInstanceId(id).list();
		for(HistoricVariableInstance hv : list){
			map.put(hv.getVariableName(), hv.getValue());
		}
		return map;
	}

	/**
	 * 每十分钟进行下载总部的流程数据
	 *
	 * @param: @throws RDPException
	 * @return: WorkflowServiceimpl
	 * @throws
	 */
	@Override
	public void executeDownload() throws RDPException {

		// 下载表单数据
		// 请假
		List<FormSyncVo> queryZBLeave = ds.queryFormDate(
				FormSQLUtil.leaveSQL, "PK_LEAVE_ID", "HRM_LEAVE");
		List<FormSyncVo> queryMDLeave = activitiEntityMapper.queryFormDate(
				"PK_LEAVE_ID", "HRM_LEAVE");
		List<FormSyncVo> queryLeave = newFormDate(queryZBLeave,
				queryMDLeave,"1");
		if (queryLeave.size() > 0) {
			for(FormSyncVo vo : queryLeave)
				activitiEntityMapper.updateFormStatus(vo);
		}
		// 库存调整
		List<FormSyncVo> queryZBStock = ds.queryFormDate(
				FormSQLUtil.stockSQL, "PK_STGADJ_ID", "scm_stg_adj");
		List<FormSyncVo> queryMDStock = activitiEntityMapper.queryFormDate(
				"PK_STGADJ_ID", "scm_stg_adj");
		List<FormSyncVo> queryStock = newFormDate(queryZBStock,
				queryMDStock,"1");
		if (queryStock.size() > 0) {
			for(FormSyncVo vo : queryStock)
				activitiEntityMapper.updateFormStatus(vo);
		}
		//库存调整特殊处理
		List<FormSyncVo> queryZBStockData = ds.queryStockDate();
		List<FormSyncVo> queryMDStockData = activitiEntityMapper.queryStockDate();
		List<FormSyncVo> queryStockData = newFormDate(queryZBStockData,
				queryMDStockData,"2");
		if (queryStockData.size() > 0) {
			for(FormSyncVo vo : queryStockData)
				activitiEntityMapper.updateStockCnt(vo);
		}
		// 付款
		List<FormSyncVo> queryZBPay = ds.queryFormDate(FormSQLUtil.paySQL,
				"PK_PAYFORM_ID", "scm_payform");
		List<FormSyncVo> queryMDPay = activitiEntityMapper.queryFormDate(
				"PK_PAYFORM_ID", "scm_payform");
		List<FormSyncVo> queryPay = newFormDate(queryZBPay, queryMDPay,"1");
		if (queryPay.size() > 0) {
			for(FormSyncVo vo : queryPay)
				activitiEntityMapper.updateFormStatus(vo);
		}
		// 采购
		List<FormSyncVo> queryZBOrder = ds.queryFormDate(
				FormSQLUtil.orderSQL, "PK_PURORD_ID", "scm_pur_order");
		List<FormSyncVo> queryMDOrder = activitiEntityMapper.queryFormDate(
				"PK_PURORD_ID", "scm_pur_order");
		List<FormSyncVo> queryOrder = newFormDate(queryZBOrder,
				queryMDOrder,"1");
		if (queryOrder.size() > 0) {
			for(FormSyncVo vo : queryOrder)
				activitiEntityMapper.updateFormStatus(vo);
		}
		// 促销
		List<FormSyncVo> queryZBDiscount = ds.queryFormDate(
				FormSQLUtil.discountSQL, "PK_CAMP_ID", "pro_campaign");
		List<FormSyncVo> queryMDDiscount = activitiEntityMapper
				.queryFormDate("PK_CAMP_ID", "pro_campaign");
		List<FormSyncVo> queryDiscount = newFormDate(queryZBDiscount,
				queryMDDiscount,"1");
		if (queryDiscount.size() > 0) {
			for(FormSyncVo vo : queryDiscount)
				activitiEntityMapper.updateFormStatus(vo);
		}
		// 定价
		List<FormSyncVo> queryZBPrice = ds.queryFormDate(
				FormSQLUtil.priceSQL, "PK_PRICE_ID", "scm_prd_price");
		List<FormSyncVo> queryMDPrice = activitiEntityMapper.queryFormDate(
				"PK_PRICE_ID", "scm_prd_price");
		List<FormSyncVo> queryPrice = newFormDate(queryZBPrice,
				queryMDPrice,"1");
		if (queryPrice.size() > 0) {
			for(FormSyncVo vo : queryPrice)
				activitiEntityMapper.updateFormStatus(vo);
		}
		// 客户服务
		List<FormSyncVo> queryZBServer = ds.queryFormDate(
				FormSQLUtil.serverSQL, "PK_CAREFORM_ID", "CAR_CARE_FORM");
		List<FormSyncVo> queryMDServer = activitiEntityMapper
				.queryFormDate("PK_CAREFORM_ID", "CAR_CARE_FORM");
		List<FormSyncVo> queryServer = newFormDate(queryZBServer,
				queryMDServer,"1");
		if (queryServer.size() > 0) {
			for(FormSyncVo vo : queryServer)
				activitiEntityMapper.updateFormStatus(vo);
		}

		// 进行下载act_re_procdef
		List<ActivitiEntity> newProcdef = newDate(ds.queryProcdef(),activitiEntityMapper.queryProcdef());
		if(newProcdef.size() != 0){
			activitiEntityMapper.insertProcdef(newProcdef);
		}
		//进行下载act_ru_execution
		List<ActivitiEntity> newExecution = newDate(ds.queryExecution(),activitiEntityMapper.queryExecution());
		if(newExecution.size() != 0){
			activitiEntityMapper.insertExecution(newExecution);
		}
		//进行下载act_ru_task
		List<ActivitiEntity> newTask = newDate(ds.queryTask(),activitiEntityMapper.queryTask());
		if(newTask.size() != 0){
			activitiEntityMapper.insertTask(newTask);
		}
		//进行下载act_ru_identitylink
		List<ActivitiEntity> newIdentitylink = newDate(ds.queryIdentitylink(),activitiEntityMapper.queryIdentitylink());
		if(newIdentitylink.size() != 0){
			activitiEntityMapper.insertIdentitylink(newIdentitylink);
		}
		//进行下载act_hi_procinst
		List<ActivitiEntity> newProcinst = newDate(ds.queryProcinst(),activitiEntityMapper.queryProcinst());
		if(newProcinst.size() != 0){
			activitiEntityMapper.insertProcinst(newProcinst);
		}
		//进行下载act_hi_comment
		List<ActivitiEntity> newComment = newDate(ds.queryComment(),activitiEntityMapper.queryComment());
		if(newComment.size() != 0){
			activitiEntityMapper.insertComment(newComment);
		}
		//进行下载act_hi_varinst
		List<ActivitiEntity> newVarinst = newDate(ds.queryVarinst(),activitiEntityMapper.queryVarinst());
		if(newVarinst.size() != 0){
			activitiEntityMapper.insertVarinst(newVarinst);
		}
		//进行下载act_hi_taskinst
		List<ActivitiEntity> newTaskinst = newDate(ds.queryTaskinst(),activitiEntityMapper.queryTaskinst());
		if(newTaskinst.size() != 0){
			activitiEntityMapper.insertTaskinst(newTaskinst);
		}
		//进行下载act_hi_identitylink
		List<ActivitiEntity> newHiIdentitylink = newDate(ds.queryHiIdentitylink(),activitiEntityMapper.queryHiIdentitylink());
		if(newHiIdentitylink.size() != 0){
			activitiEntityMapper.insertHiIdentitylink(newHiIdentitylink);
		}
	}
	
	/**
	 * 得到新数据
	 * @param data1：总部数据
	 * @param data2：门店数据
	 * @return
	 * @date: 2014年10月9日
	 */
	public List<ActivitiEntity> newDate(List<ActivitiEntity> data1,List<ActivitiEntity> data2){
		List<ActivitiEntity> list = new ArrayList<ActivitiEntity>();
		if(null != data1 && null != data2){
			for(ActivitiEntity ae1 : data1){
				boolean flag = true;
				for(ActivitiEntity ae2 : data2){
					if(ae1.getId().equals(ae2.getId())){
						flag = false;
						break;
					}
				}
				if(flag)
					list.add(ae1);
			}
		}
		return list;
	}
	
	/**
	 * 去除两个相同的数据
	 * @param data1
	 * @param data2
	 * @param flag ： 1表示表单数据  2表示库存数量
	 * @return
	 * @date: 2014年11月4日
	 */
	public List<FormSyncVo> newFormDate(List<FormSyncVo> data1,List<FormSyncVo> data2,String flag){
		List<FormSyncVo> list = new ArrayList<FormSyncVo>();
		if(data1.size()>0 && data2.size()>0){
			for(FormSyncVo ws1 : data1){
				for(FormSyncVo ws2 : data2){
					if(flag.equals("1")){
						if(ws1.getId().equals(ws2.getId()) && !ws1.getStatus().equals(ws2.getStatus())){
							list.add(ws1);
						}
					}else if(flag.equals("2")){
						if(ws1.getId().equals(ws2.getId()) && ws1.getStgCnt()!=ws2.getStgCnt()){
							list.add(ws1);
						}
					}
				}
			}
		}
		return list;
	}
	
	

}
